﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using MAPIdotnet;
using Microsoft.Win32;
using Microsoft.WindowsMobile.PocketOutlook;
using Microsoft.WindowsMobile.PocketOutlook.MessageInterception;
using Terranova.API;
//using Koolwired.Imap;
namespace SMSRulez
{
    public partial class Rules : Form
    {
        string schTime = "00:00";
        readonly string ARCHSMS = "ArchivedSMS";
        private MAPI mapi;
        private IMAPIMsgStore[] stores;
        IMAPIFolderID[] subFolders = null;
        IMAPIFolder folder = null;
        IMAPIFolder folders = null;
        IMAPIFolder smsFolder = null;
        IMAPIFolder gmailFolder = null;
        OutlookSession myOutlook = new OutlookSession();
        //enum sqlAction { Insert, Update, Delete, Select, Create };
        enum panelsVal { None, Password, AllMessages, NewPassword };
        static string location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
        List<String> messageContacts = new List<string>();
        private MessageInterceptor mi;
        DataTable tableRule;// = new DataTable();
        SmsAccount SMS = null;
        internal string PASSWORD = string.Empty;
        string smsName = string.Empty;
        bool changePassword = false;
        List<string> messagesAll = new List<string>();
        bool resetPassword = false;
        HiddenFolderClass hideFolder;

        DB db;
        public Rules(string[] args)
        {
            db = new DB(location);
            if (args.Length >= 1)
            {
                resetPassword = true;
            }
            InitializeComponent();
        }
        private void RefreshScreen()
        {
            Win32.SendMessage((IntPtr)Win32.HWND_BROADCAST, Win32.WM_WININICHANGE, 0xF2, 0);
        }

        private void SetMessageNotification(bool on)
        {
            if (on)
            {
                //"[HKEY_CURRENT_USER\ControlPanel\Notifications\{A877D65B-239C-47a7-9304-0D347F580408}]" 11 0
                Registry.CurrentUser.CreateSubKey("ControlPanel").CreateSubKey("Notifications").CreateSubKey("{A877D65B-239C-47a7-9304-0D347F580408}").SetValue("Options", 11, RegistryValueKind.DWord);

            }
            else
            {
                //Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("Microsoft").CreateSubKey("Inbox").CreateSubKey("Settings").SetValue("SMSAvailable", 0, RegistryValueKind.DWord);
                Registry.CurrentUser.CreateSubKey("ControlPanel").CreateSubKey("Notifications").CreateSubKey("{A877D65B-239C-47a7-9304-0D347F580408}").SetValue("Options", 0, RegistryValueKind.DWord);
            }
            Registry.ClassesRoot.Flush();
            Registry.LocalMachine.Flush();
            Registry.Users.Flush();
            Registry.CurrentUser.Flush();
           // RefreshScreen();
        }
        #region RULEWORKS
        private void Rules_Load(object sender, EventArgs e)
        {
            SMS = myOutlook.SmsAccount;
            smsName = SMS.Name.Trim().ToUpper();

            db.SetConnection("CREATE TABLE IF NOT EXISTS MessageRules(Folder char(20) , Rule char(20) UNIQUE , Action char(6), AutoRun char(1))", DB.sqlAction.Create, out tableRule);
            db.SetConnection("CREATE TABLE IF NOT EXISTS ContactRules(Folder char(20) , Rule char(20) UNIQUE , Action char(6), AutoRun char(1))", DB.sqlAction.Create, out tableRule);
            db.SetConnection("CREATE TABLE IF NOT EXISTS Password(password char(40))", DB.sqlAction.Create, out tableRule);
            //SetConnection("CREATE TABLE IF NOT EXISTS SMSFolder(smsName char(10))", sqlAction.Create);
            //SetConnection("DELETE FROM SMSFolder", sqlAction.Delete);
            //SetConnection("INSERT INTO SMSFolder (smsName) VALUES('" + smsName + "')",sqlAction.Insert);
            if (resetPassword)
            { db.SetConnection("DELETE FROM Password", DB.sqlAction.Delete, out tableRule); }
            mapi = new MAPI();
            stores = mapi.MessageStores;
            FillSMSFolders();
            //FillContacts();
            ddlRuleOpts.SelectedIndex = 0;
            ddlAction.SelectedIndex = 0;
            ddlContactOpts.SelectedIndex = 0;
            RegRW();
            
            menu_AUTORUN.Checked = RegIsChecked("MAIN");
            menuNotify.Checked = RegIsChecked("NOTIFY");
            menuDefNotify.Checked = RegIsChecked("DEF");
            menuNotiHid.Checked = RegIsChecked("HIDE");
           
            #region PANELS
            panelPrivate.Visible = false;
            panelPrivate.Enabled = false;
            panelPrivate.Controls.Add(lblPrivateInbox);
            ////////////////////////////////////////////////////
            panelPassword.Visible = false;
            panelPassword.Controls.Add(txtPassword);
            panelPassword.Controls.Add(lblPaswd);
            panelPassword.Controls.Add(btnPaswOK);
            panelPassword.Controls.Add(btnPaswdCancel);
            panelPassword.Controls.Add(chkChangePaswd);
            ////////////////////////////////////////////////////
            panelFolder.Controls.Add(txtFolderName);
            panelFolder.Controls.Add(lblFolderName);
            panelFolder.Controls.Add(btnOK);
            panelFolder.Controls.Add(btnCancel);
            panelFolder.Visible = false;
            ///////////////////////////////////////////////////
            panelNewPassword.Controls.Add(btnNewPswdCancel);
            panelNewPassword.Controls.Add(btnNewPswdOk);
            panelNewPassword.Visible = false;
            ///////////////////////////////////////////////////
            panelBlack.Visible = false;
            panelBlack.Enabled = false;
            panelBlack.SendToBack();
            ///////////////////////////////////////////////////

            #endregion PANELS
            tabRules.SelectedIndexChanged += new EventHandler(enableAdd);
            listRules.ItemCheck += new ItemCheckEventHandler(WriteRunRules);
            lbl.Text = "Developed and Maintained by Mohit Sapru.\nIf you find it useful please donate to the developer :)\n\n\nTo donate, check for updates or any suggestions plz visit:";
        }

        private void FillSMSFolders()
        {

            for (int i = 0, length = stores.Length; i < length; i++)
            {
                IMAPIMsgStore store = stores[i];
                IMAPIMsgStore mailStore = stores[i];
                //if (string.Compare(mailStore.DisplayName, "Gmail", true) == 0)
                //{
                //    mailFolder = mailStore.RootFolder.OpenFolder();
                //    mailSubFolder = mailFolder.GetSubFolders((int)mailFolder.NumSubFolders);
                //    mail = FetchMailFolderId("SMS");// mailStore.SentMailFolder.OpenFolder(); 
                //}
                if (string.Compare(store.DisplayName.ToUpper(), smsName, StringComparison.OrdinalIgnoreCase | StringComparison.Ordinal) == 0)
                {
                    folder = store.RootFolder.OpenFolder();
                    smsFolder = folder;
                    subFolders = folder.GetSubFolders((int)folder.NumSubFolders);
                    listFolder.BeginUpdate();
                    listFolderMessage.BeginUpdate();
                    listFolderArch.BeginUpdate();
                    ListViewItem folderList;
                    foreach (IMAPIFolderID fId in subFolders)
                    {
                        folders = fId.OpenFolder();
                        if (!ARCHSMS.Equals(folders.DisplayName.Trim()))
                        {
                            listFolder.Items.Add(folders.DisplayName.Trim());
                            listFolderMessage.Items.Add(folders.DisplayName.Trim());
                            folderList = new ListViewItem(folders.DisplayName.Trim());
                            folderList.Checked = false;
                            listFolderArch.Items.Add(folderList);
                            ddlFilterFolder.Items.Add(folders.DisplayName.Trim());
                        }
                    }

                    listFolderArch.EndUpdate();
                    listFolder.EndUpdate();
                    listFolderMessage.EndUpdate();
                    listFolderArch.Refresh();
                    IMAPIFolder inbox = store.ReceiveFolder.OpenFolder();
                    inbox.SortMessagesBySenderName(TableSortOrder.TABLE_SORT_DESCEND);
                    List<IMAPIMessage> messages = new List<IMAPIMessage>();// inbox.GetNextMessages(inbox.NumSubItems);
                    for (int pos = 0; pos < inbox.NumSubItems; pos++)
                    {
                        try
                        {
                            //inbox.SeekMessages(pos);
                            messages.Add((IMAPIMessage)inbox.GetNextMessages(1).GetValue(0));
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                    FillContactsFromMessage(messages.ToArray());
                    break;
                }
            }
        }

        private void FillContactsFromMessage(IMAPIMessage[] messages)
        {
            List<IMAPIMessageID> ruleMessages = new List<IMAPIMessageID>();

            for (int i = 0, length = messages.Length; i < length; i++)
            {
                IMAPIMessage msg = messages[i];
                msg.PopulateProperties(EMessageProperties.Sender);
                IMAPIContact sender = msg.Sender;
                if (sender != null)
                {
                    if (!messageContacts.Contains(sender.Name.Trim()))
                    {
                        messageContacts.Add(sender.Name.Trim());
                    }
                }
            }
            messageContacts.Sort();
        }

        private void FillContacts()
        {

            string contactName = string.Empty;
            //listContact.Items.Clear();
            listVContact.Items.Clear();
            listVContact.BeginUpdate();
            if (ddlContactOpts.SelectedIndex == 0)
            {
                foreach (string contact in messageContacts)
                {
                    //listContact.Items.Add(contact.ToUpper().Trim());
                    listVContact.Items.Add(new ListViewItem(contact.ToUpper().Trim()));
                }
            }
            else
            {
                if (ddlContactOpts.SelectedIndex == 1)
                {
                    myOutlook.Contacts.Items.Sort("FirstName", false);
                }
                else if (ddlContactOpts.SelectedIndex == 2)
                {
                    myOutlook.Contacts.Items.Sort("LastName", false);
                }
                else if (ddlContactOpts.SelectedIndex == 3)
                {
                    panelBlack.Visible = true;
                    panelBlack.Enabled = true;
                    panelBlack.BringToFront();
                    panelwild.BringToFront();
                    panelwild.Enabled = true;
                    panelwild.Visible = true;

                }
                if (ddlContactOpts.SelectedIndex != 3)
                {
                    foreach (Contact contactList in myOutlook.Contacts.Items)
                    {
                        if (ddlContactOpts.SelectedIndex == 1)
                        {
                            contactName = contactList.FirstName.ToString().Trim();
                        }
                        else if (ddlContactOpts.SelectedIndex == 2)
                        {
                            contactName = contactList.LastName.ToString().Trim();
                        }
                        if (!string.IsNullOrEmpty(contactName.Trim()))
                        {
                            //listContact.Items.Add(contactName.ToUpper().Trim());
                            listVContact.Items.Add(new ListViewItem(contactName.ToUpper().Trim()));
                        }
                    }
                }


            }
            listVContact.EndUpdate();
            //listContact.Refresh();
            listVContact.Refresh();
            //myOutlook.Dispose();
        }

        private void enableAdd(object sender, EventArgs e)
        {
            if (tabRules.SelectedIndex == 0 || tabRules.SelectedIndex == 1)
            {
                menu_ADD.Enabled = true;
                menu_ADD.Text = "Add";
            }
            else
            {
                txtPassword.Text = "Enter Password";
                txtPassword.Refresh();
                ShowPanels(panelsVal.None);
                menu_ADD.Enabled = true;
                menu_ADD.Text = "Delete";
                listRules.Items.Clear();
                comboRules.Items.Clear();
                panel1.Controls.Add(radioContactRules);
                panel1.Controls.Add(radioMessageRule);
                radioRules_CheckedChanged(null, null);
            }

        }

        private void FillSelectedRule(string selectedFolder, string rule)
        {
            string command = string.Empty;
            string tableName = "ContactRules";
            ListViewItem ruleView = null;
            tableRule.Clear();
            string ruleName = string.Empty;
            string action = string.Empty;
            string autorun = string.Empty;
            if (rule.Equals("MESSAGE"))
            {
                tableName = "MessageRules";
            }
            command = "SELECT DISTINCT Rule, Action, AutoRun FROM " + tableName + " WHERE Folder = '" + selectedFolder + "'";
            db.SetConnection(command, DB.sqlAction.Select, out tableRule);
            listRules.ItemCheck -= new ItemCheckEventHandler(WriteRunRules);
            listRules.BeginUpdate();
            foreach (DataRow row in tableRule.Rows)
            {
                ruleName = row[0].ToString();
                action = row[1].ToString();
                autorun = row[2].ToString();
                ruleView = new ListViewItem(new string[] { string.Empty, ruleName, action });

                if (autorun.Equals("Y"))
                {
                    ruleView.Checked = true;
                }
                else
                {
                    ruleView.Checked = false;
                }
                listRules.Items.Add(ruleView);

            }
            listRules.EndUpdate();
            tableRule.Clear();
            listRules.Refresh();
            listRules.ItemCheck += new ItemCheckEventHandler(WriteRunRules);
        }

        //Add/ Delete Button
        private void menuItem2_Click(object sender, EventArgs e)
        {
            string selectedFolder = string.Empty;
            string selectedContact = string.Empty;
            string message = string.Empty;
            string action = "MOVE";
            string Command = string.Empty;
            #region CONTACT
            if (tabRules.SelectedIndex == 0)
            {
                lblContact.Text = "";
                lblContact.Refresh();
                menu_ADD.Text = "Add";
                if (listFolder.SelectedItem != null)
                    selectedFolder = listFolder.SelectedItem.ToString().Trim();
                //if (listContact.SelectedItem != null)
                //  selectedContact = listContact.SelectedItem.ToString().Trim().ToUpper();
                if (listVContact.FocusedItem != null)
                    selectedContact = listVContact.FocusedItem.Text.ToUpper().Trim();
                if (string.Compare(ddlRuleOpts.SelectedItem.ToString().Trim(), "HIDE", StringComparison.Ordinal | StringComparison.OrdinalIgnoreCase) != 0)
                {
                    if (!string.IsNullOrEmpty(selectedContact.Trim()) && !string.IsNullOrEmpty(selectedFolder.Trim()))
                    {
                        Command = "SELECT Rule FROM ContactRules WHERE Rule like '" + selectedContact + "'";
                        db.SetConnection(Command, DB.sqlAction.Select, out tableRule);
                        if (tableRule.Rows.Count < 1)
                        {
                            tableRule.Clear();
                            action = ddlRuleOpts.SelectedItem.ToString().Trim();
                            Command = "INSERT INTO ContactRules (Folder,Rule,Action,AutoRun) VALUES('" + selectedFolder + "','" + selectedContact + "','" + action + "','N')";
                            db.SetConnection(Command, DB.sqlAction.Insert, out tableRule);
                            lblContact.Text = "Rule Added";
                            lblContact.Refresh();
                        }
                        else
                        {
                            MessageBox.Show("Contact Rule for " + selectedContact + " already defined...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Select both values", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    }
                }
                else
                {
                    //TODO:add hide code
                    Command = "SELECT Rule FROM ContactRules WHERE Rule like '" + selectedContact + "'";
                    db.SetConnection(Command, DB.sqlAction.Select, out tableRule);
                    if (tableRule.Rows.Count < 1)
                    {
                        tableRule.Clear();
                        action = ddlRuleOpts.SelectedItem.ToString().Trim();
                        Command = "INSERT INTO ContactRules (Folder,Rule,Action,AutoRun) VALUES('#','" + selectedContact + "','HIDE','Y')";
                        db.SetConnection(Command, DB.sqlAction.Insert, out tableRule);
                        lblContact.Text = "Rule Added";
                        lblContact.Refresh();
                    }
                    else
                    {
                        MessageBox.Show("Contact Rule for " + selectedContact + " already defined...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    }
                }
            }
            #endregion
            #region Message
            else if (tabRules.SelectedIndex == 1)
            {
                lblMssgRuleAdded.Text = "";
                lblMssgRuleAdded.Refresh();
                menu_ADD.Text = "Add";
                message = txtRuleMessage.Text.ToUpper().Trim();
                if (listFolderMessage.SelectedItem != null)
                    selectedFolder = listFolderMessage.SelectedItem.ToString().Trim();
                lblMssgRuleAdded.Text = "";
                if (!string.IsNullOrEmpty(message.Trim()) && !string.IsNullOrEmpty(selectedFolder.Trim()))
                {
                    Command = "SELECT Rule FROM MessageRules WHERE Rule LIKE '%" + message + "%'";
                    db.SetConnection(Command, DB.sqlAction.Select, out tableRule);
                    if (tableRule.Rows.Count < 1)
                    {
                        tableRule.Clear();
                        action = ddlAction.SelectedItem.ToString().Trim();
                        Command = "INSERT INTO MessageRules (Folder,Rule,Action,AutoRun) VALUES('" + selectedFolder + "','" + message + "','" + action + "','N')";
                        db.SetConnection(Command, DB.sqlAction.Insert, out tableRule);
                        lblMssgRuleAdded.Text = "Message rule added";
                        lblMssgRuleAdded.Refresh();
                    }
                    else
                    {
                        MessageBox.Show("Message Rule for/like " + message + " already defined...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    }

                }
                else
                {
                    MessageBox.Show("Select both values", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                }
                txtRuleMessage.Text = "";
                txtRuleMessage.Refresh();
            }
            #endregion
            #region Existing
            //delete
            else if (tabRules.SelectedIndex == 2)
            {
                menu_ADD.Text = "Delete";
                radioMessageRule.Refresh();
                radioContactRules.Refresh();
                comboRules.Refresh();
                listRules.Refresh();
                string FolderName = string.Empty;
                string ItemName = string.Empty;
                try
                {
                    FolderName = comboRules.SelectedItem.ToString().Trim();
                    ItemName = listRules.FocusedItem.SubItems[1].Text.ToString().Trim();
                }
                catch
                {
                    FolderName = "-1";
                    ItemName = "-1";
                }
                if (FolderName.Equals("-1") || ItemName.Equals("-1"))
                {
                    MessageBox.Show("Select both values", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                }
                else
                {

                    string folder = string.Empty;
                    if (radioMessageRule.Checked == true)
                    {
                        listRules.Items.RemoveAt(listRules.FocusedItem.Index);
                        listRules.Refresh();
                        Command = "DELETE FROM MessageRules WHERE Folder = '" + FolderName + "' AND Rule = '" + ItemName + "'";
                        db.SetConnection(Command, DB.sqlAction.Delete, out tableRule);
                    }
                    else
                    {
                        listRules.Items.RemoveAt(listRules.FocusedItem.Index);
                        listRules.Refresh();
                        Command = "DELETE FROM ContactRules WHERE Folder = '" + FolderName + "' AND Rule = '" + ItemName + "'";
                        db.SetConnection(Command, DB.sqlAction.Delete, out tableRule);
                    }

                }
            }
            #endregion
            #region ABOUT
            else
            {
                menu_ADD.Text = "";
                menu_ADD.Enabled = false;
            }
            #endregion

        }

        private void menuItem3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
            Process pc = new Process();
            pc.StartInfo = new ProcessStartInfo(location + @"\" + "SMSRules.exe", null);
            pc.Start();
        }

        //private void listContact_SelectedValueChanged(object sender, EventArgs e)
        //{
        //  lblContact.Text = listContact.SelectedItem.ToString().Trim();
        //lblContact.Refresh();
        //}

        private void listFolder_SelectedValueChanged(object sender, EventArgs e)
        {
            lblFolder.Text = listFolder.SelectedItem.ToString().Trim();
        }

        private void comboRules_SelectedValueChanged(object sender, EventArgs e)
        {
            listRules.Items.Clear();
            try
            {
                if (radioContactRules.Checked == true)
                {
                    FillSelectedRule(comboRules.SelectedItem.ToString(), "CONTACT");
                }
                else
                {
                    FillSelectedRule(comboRules.SelectedItem.ToString(), "MESSAGE");
                }
            }
            catch
            {
            }
        }
        //Existing
        private void radioRules_CheckedChanged(object sender, EventArgs e)
        {
            comboRules.Items.Clear();
            string folder = string.Empty;
            string command = string.Empty;
            tableRule.Clear();
            listRules.Items.Clear();
            listRules.Refresh();
            if (radioContactRules.Checked == true)
            {
                command = "SELECT DISTINCT Folder FROM ContactRules";
            }
            else
            {
                command = "SELECT DISTINCT Folder FROM MessageRules";
            }

            db.SetConnection(command, DB.sqlAction.Select, out tableRule);
            foreach (DataRow item in tableRule.Rows)
            {
                comboRules.Items.Add(item[0].ToString().Trim());
            }

        }

        private void radioDefault_CheckedChanged(object sender, EventArgs e)
        {
            FillContacts();
        }

        private void linkAbt_Click(object sender, EventArgs e)
        {
            Process.Start("IExplore", "http://forum.xda-developers.com/showpost.php?p=4882734&postcount=1");

        }
        #endregion RULEWORKS

        #region MENUWORKS
        private void menu_AUTORUN_Click(object sender, EventArgs e)
        {
            if (menu_AUTORUN.Checked)
            {
                menu_AUTORUN.Checked = false;
                RegSetStatus(false, "MAIN");
                AutoRun(false);
                //SetMessageNotification(true);
            }
            else
            {
                menu_AUTORUN.Checked = true;
                RegSetStatus(true, "MAIN");
                AutoRun(true);
                //SetMessageNotification(false);
            }
        }

        private void AutoRun(bool enable)
        {
            string autoLaunchExePath = location + @"\" + "AutoLaunch.exe";
            Process pc = new Process();
            if (enable)
            {
                if (!(ProcessCE.IsRunning(autoLaunchExePath)))
                {
                    pc.StartInfo.FileName = autoLaunchExePath;
                    pc.Start();
                    MessageBox.Show("AutoRun Running!", "Info");
                }
                menu_AUTORUN.Checked = true;
            }
            else
            {

                bool killed = false;
                bool killSuccess = false;
                if (ProcessCE.IsRunning(autoLaunchExePath))
                {
                    while (!killed)
                    {
                        killed = ProcessCE.FindAndKill(autoLaunchExePath);
                        killSuccess = true;
                    }
                }
                bool appRegistered = MessageInterceptor.IsApplicationLauncherEnabled("SMSRules");
                if (appRegistered)
                {
                    try
                    {
                        mi = new MessageInterceptor("SMSRules", false); //Load the existing settings
                        // mi.MessageReceived -= SmsInterceptor_MessageReceived_OnThread;
                        mi.DisableApplicationLauncher();
                        mi.Dispose();
                        killSuccess = true;
                    }
                    catch
                    {
                        killSuccess = false;
                    }
                }
                RegistryKey rules = Registry.LocalMachine.CreateSubKey("Software").CreateSubKey("Microsoft").CreateSubKey("Inbox").CreateSubKey("Rules");
                int ruleCount = rules.SubKeyCount;
                if (ruleCount >= 1)
                {
                    try
                    {
                        foreach (string key in rules.GetSubKeyNames())
                        {
                            if (key.Equals("ServerRemote"))
                            {
                            }
                            else if (key.Equals("SMSRules"))
                            {
                                rules.DeleteSubKeyTree(key);
                            }
                            else
                            {
                                rules.DeleteSubKeyTree(key);
                            }
                        }
                        killSuccess = true;
                    }
                    catch
                    {
                        killSuccess = false;
                    }
                }
                if (killSuccess)
                {
                    MessageBox.Show("AutoRun Stopped!", "Info");
                    menu_AUTORUN.Checked = false;
                }
                else
                {
                    menu_AUTORUN.Checked = true;
                    MessageBox.Show("Error stopping AutoRun!", "Info");
                }
            }

        }

        private void menu_MENU_Popup(object sender, EventArgs e)
        {
            menu_AUTORUN.Checked = RegIsChecked("MAIN");
            menuNotify.Checked = RegIsChecked("NOTIFY");

            if (tabRules.SelectedIndex != 0)
            {
                menu_AddFolder.Enabled = false;
                menu_DeleteFolder.Enabled = false;
            }
            else
            {
                menu_AddFolder.Enabled = true;
                menu_DeleteFolder.Enabled = true;
            }

            if (tabRules.SelectedIndex == 4)
            {
                menu_Personal.Enabled = true;
                menu_Show.Enabled = true;
            }
            else
            {
                menu_Personal.Enabled = false;
                menu_Show.Enabled = false;
            }
        }

        private void btnAll_Click(object sender, EventArgs e)
        {
            Cursor.Show();
            Cursor.Current = Cursors.WaitCursor;
            foreach (ListViewItem lv in listRules.Items)
            {
                lv.Checked = true;
            }
            Cursor.Current = Cursors.Default;
            Cursor.Hide();
        }

        private void btnNone_Click(object sender, EventArgs e)
        {
            Cursor.Show();
            Cursor.Current = Cursors.WaitCursor;
            foreach (ListViewItem lv in listRules.Items)
            {
                lv.Checked = false;
            }
            Cursor.Current = Cursors.Default;
            Cursor.Hide();
        }

        private void WriteRunRules(object sender, ItemCheckEventArgs e)
        {
            int index = e.Index;
            string command = string.Empty;
            string tableName = string.Empty;
            string folderName = string.Empty;
            string ruleName = string.Empty;
            string action = string.Empty;
            folderName = comboRules.SelectedItem.ToString();
            ruleName = listRules.Items[index].SubItems[1].Text.Trim().ToUpper();
            if (e.NewValue == CheckState.Checked)
            {
                if (radioContactRules.Checked)
                {
                    action = "Y";
                    tableName = "ContactRules";
                }
                else
                {
                    tableName = "MessageRules";
                    action = "Y";
                }
            }
            else
            {
                if (radioContactRules.Checked)
                {
                    tableName = "ContactRules";
                    action = "N";
                }
                else
                {
                    tableName = "MessageRules";
                    action = "N";
                }
            }
            command = "UPDATE " + tableName + " SET AutoRun = '" + action + "' WHERE Folder = '" + folderName + "' AND Rule = '" + ruleName + "'";
            db.SetConnection(command, DB.sqlAction.Update, out tableRule);
        }


        #endregion MENUWORKS

        #region RegistryWork
        RegistryKey reg = null;
        private void RegRW()
        {
            try
            {
                reg = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("SmsRule");
            }
            catch
            {
                MessageBox.Show("Error creating registry", "ERROR");
                this.Close();
            }
            {
                if (reg == null)
                {
                    reg = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("SmsRule");
                }
                if (reg.ValueCount < 6)
                {
                    reg.SetValue("InfoChecked", 0);
                    reg.SetValue("notify", 0);
                    reg.SetValue("notifyHide", 0);
                    reg.SetValue("notifyDef", 0);
                    reg.SetValue("schedule",schTime);
                    reg.SetValue("scheduleSet", 0);
                }
            }


        }

        private bool RegIsChecked(string info)
        {
            object status = null;
            switch (info)
            {
                case "MAIN":
                    status = reg.GetValue("InfoChecked");
                    break;
                case "NOTIFY":
                    status = reg.GetValue("notify");
                    break;
                case "HIDE":
                    status = reg.GetValue("notifyHide");
                    break;
                case "DEF":
                    status = reg.GetValue("notifyDef");
                    break;
             
            }

            if (status.ToString().Equals("1"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void RegSetStatus(bool status, string info)
        {
            string regString = "InfoChecked";
            switch (info)
            {
                case "MAIN":
                    regString = "InfoChecked";
                    break;
            }

            if (status)
            {
                reg.SetValue(regString, 1);
            }
            else
            {
                reg.SetValue(regString, 0);
            }
        }

        #endregion

        #region FOLDERWORKS
        private void CreateFolder(string folderName)
        {
            if (!string.IsNullOrEmpty(folderName.Trim()))
            {
                try
                {
                    IMAPIFolder newFolder = smsFolder.CreateFolder(folderName, false);
                    if (newFolder != null)
                    {
                        listFolderMessage.Items.Add(folderName.Trim());
                        listFolder.Items.Add(folderName.Trim());
                        listFolder.Refresh();
                        listFolderMessage.Refresh();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error Creating Folder", "Error!");
                }

            }
        }

        private IMAPIFolder OpenFolder(string folderName)
        {
            if (!string.IsNullOrEmpty(folderName.Trim()))
            {
                try
                {
                    IMAPIFolder newFolder = smsFolder.CreateFolder(folderName, true);
                    return newFolder;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error Opening Folder", "Error!");
                    return null;
                }
            }
            return null;
        }

        private IMAPIFolder CreateArchiveSubFolders(IMAPIFolder archiveFolder, string subFolderName)
        {
            string MMMdd = DateTime.Now.ToString("MMMddyy");
            if (archiveFolder != null)
            {
                if (!string.IsNullOrEmpty(subFolderName.Trim()))
                {
                    string subFolderNameDate = subFolderName + "_" + MMMdd;
                    try
                    {
                        return archiveFolder.CreateFolder(subFolderName, true).CreateFolder(subFolderNameDate, true);
                        //return archiveFolder.CreateFolder(subFolderName,true);
                    }
                    catch
                    {
                        return null;
                    }
                }
            }
            return null;
        }

        private void menu_AddFolder_Click(object sender, EventArgs e)
        {
            panelBlack.Visible = true;
            panelBlack.Enabled = true;
            panelBlack.BringToFront();
            panelFolder.Visible = true;
            panelFolder.BringToFront();

        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtFolderName.Text.Trim()))
            {
                CreateFolder(txtFolderName.Text.Trim());
                panelFolder.Visible = false;
                panelFolder.SendToBack();
                panelBlack.Visible = false;
                panelBlack.Enabled = false;
                panelBlack.SendToBack();

            }
            else
            {
                MessageBox.Show("Enter Folder Name");
            }

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            panelFolder.Visible = false;
            panelFolder.SendToBack();
            panelBlack.Visible = false;
            panelBlack.Enabled = false;
            panelBlack.SendToBack();
        }

        private void menu_DeleteFolder_Click(object sender, EventArgs e)
        {
            if (listFolder.SelectedItem != null)
            {
                string selectedFolder = listFolder.SelectedItem.ToString().Trim();
                IMAPIFolderID fid = GetFolderId(selectedFolder);
                if (fid != null)
                {
                    DialogResult result = MessageBox.Show("Deleting this folder will delete the messages in it also. Do you want to continue?", "Delete Folder?", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
                    if (result == DialogResult.OK)
                    {
                        try
                        {
                            smsFolder.DeleteFolder(fid, true, true);
                            listFolder.SelectedIndex = 0;
                            listFolderMessage.SelectedIndex = 0;
                            listFolderMessage.Items.Remove(selectedFolder.Trim());
                            listFolder.Items.Remove(selectedFolder.Trim());
                            listFolderMessage.Refresh();
                            listFolder.Refresh();
                        }
                        catch
                        {
                            MessageBox.Show("Error deleting folder", "ERROR");
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Error retreiving folder", "ERROR");
                }
            }
            else
            {
                MessageBox.Show("Select a folder first!", "INFO");
            }
        }

        private IMAPIFolderID GetFolderId(string folderName)
        {
            subFolders = null;
            subFolders = smsFolder.GetSubFolders((int)smsFolder.NumSubFolders);
            foreach (IMAPIFolderID fId in subFolders)
            {
                folders = fId.OpenFolder();
                if (folders.DisplayName.ToUpper().Equals(folderName.ToUpper().Trim()))
                {
                    return fId;
                }
            }
            return null;

        }
        #endregion FOLDERWORKS

        #region PRIVATEWORKS
        private void ShowPrivateMessages()
        {
            ShowPanels(panelsVal.AllMessages);
            hideFolder.MoveMessagesFromHiddenFolderToPrivateFolder();
        }
        private bool CheckNewLogin()
        {
            db.SetConnection("SELECT * FROM Password", DB.sqlAction.Select, out tableRule);
            if (tableRule.Rows.Count < 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private void ValidatePrivateMessage(bool newUser)
        {
            if (newUser)
            {
                string command = "INSERT INTO Password(password) VALUES ('" + PASSWORD.Trim() + "')";
                if (db.SetConnection(command, DB.sqlAction.Insert, out tableRule))//Enter password to database
                {
                    ShowPanels(panelsVal.AllMessages);
                    hideFolder = new HiddenFolderClass(PASSWORD.Trim());
                }
                else
                {
                    ShowPanels(panelsVal.None);
                }
            }
            else
            {
                if (CheckPassword(PASSWORD))
                {
                    ShowPanels(panelsVal.AllMessages);
                }
            }

        }
        private void PasswordToKey(string password)
        {
            RijndaelManaged sa = new RijndaelManaged();
            HashAlgorithm hashAlgo = new MD5CryptoServiceProvider();
            byte[] hash = hashAlgo.ComputeHash(Encoding.UTF8.GetBytes(password));
            sa.BlockSize = hash.Length * 8;
            sa.Key = hash;
            sa.IV = hash;
            PASSWORD = Encrypt(sa);
        }
        private string Encrypt(SymmetricAlgorithm sa)
        {

            ICryptoTransform encryptor = sa.CreateEncryptor(sa.Key, sa.IV);
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] inPass = encoding.GetBytes(PASSWORD);
            MemoryStream outStream = new MemoryStream();
            CryptoStream outPass = new CryptoStream(outStream, encryptor, CryptoStreamMode.Write);
            outPass.Write(inPass, 0, inPass.Length);
            outPass.FlushFinalBlock();
            byte[] cipherTextBytes = outStream.ToArray();
            outStream.Close();
            outPass.Close();
            string cipherText = null;
            return cipherText = Convert.ToBase64String(cipherTextBytes);

        }
        private void Decrypt(SymmetricAlgorithm sa)
        {
            ICryptoTransform decryptor = sa.CreateDecryptor(sa.Key, sa.IV);
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] inPass = encoding.GetBytes(PASSWORD);
            MemoryStream outStream = new MemoryStream(inPass);
            CryptoStream outPass = new CryptoStream(outStream, decryptor, CryptoStreamMode.Read);
            byte[] plainTextBytes = new byte[inPass.Length];
            int decryptedByteCount = outPass.Read(plainTextBytes, 0, plainTextBytes.Length);
            outStream.Close();
            outPass.Close();
            string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
        }
        #endregion PRIVATEWORKS

        #region PASSWORD
        string passwordTryOne = string.Empty;
        string passwordTryTwo = string.Empty;
        int newPasswordCount = 0;
        private void ConfirmNewPassword()
        {
            lblPaswd.Text = "Confirm New Password";
            lblPaswd.Refresh();
            txtPassword.Text = "";
            txtPassword.Refresh();
        }

        private void SetNewPassword()
        {
            if (!string.IsNullOrEmpty(PASSWORD.Trim()))
            {
                PasswordToKey(PASSWORD);
                string command = "DELETE FROM Password";
                if (db.SetConnection(command, DB.sqlAction.Delete, out tableRule))
                {
                    command = "INSERT INTO Password(password) VALUES ('" + PASSWORD.Trim() + "')";
                    if (db.SetConnection(command, DB.sqlAction.Insert, out tableRule))//Enter password to database
                    {
                        ShowPanels(panelsVal.AllMessages);
                    }
                    else
                    {
                        ShowPanels(panelsVal.None);
                    }
                }
                else
                {
                    ShowPanels(panelsVal.None);
                }
            }
            else
            {
                MessageBox.Show("Password can`t be left empty.", "ERROR");
            }
        }
        private void btnNewPswdOk_Click(object sender, EventArgs e)
        {
            newPasswordCount++;
            if (newPasswordCount > 2)
            {
                newPasswordCount = 1;
            }
            if (newPasswordCount == 1)
            {
                passwordTryOne = txtPassword.Text;
                ConfirmNewPassword();
            }
            if (newPasswordCount == 2)
            {
                passwordTryTwo = txtPassword.Text;

                if (passwordTryOne.Equals(passwordTryTwo))
                {
                    PASSWORD = txtPassword.Text;
                    SetNewPassword();
                }
                else
                {
                    MessageBox.Show("Please enter new password carefully!!", "Alert");
                    ShowPanels(panelsVal.None);
                }
            }



        }
        private void btnNewPswdCancel_Click(object sender, EventArgs e)
        {
            ShowPanels(panelsVal.Password);
            lblPaswd.Text = "Enter Password";
            lblPaswd.Refresh();
            chkChangePaswd.Checked = false;

        }
        private void chkChangePaswd_CheckStateChanged(object sender, EventArgs e)
        {
            if (chkChangePaswd.Checked)
            {
                lblPaswd.Text = "Enter Old Password";
                lblPaswd.Refresh();
                changePassword = true;
            }
            else
            {
                changePassword = false;
                lblPaswd.Text = "Enter Password";
                lblPaswd.Refresh();
            }

        }
        private void btnPaswOK_Click(object sender, EventArgs e)
        {
            setPassword(CheckNewLogin());
        }
        private void menu_Show_Click(object sender, EventArgs e)
        {
            txtPassword.Text = "";
            chkChangePaswd.Checked = false;
            ShowPanels(panelsVal.Password);
            txtPassword.Focus();
            if (CheckNewLogin())
                MessageBox.Show("Enter New Password!", "New Password");
        }
        private void setPassword(bool newLogin)
        {

            if (!string.IsNullOrEmpty(txtPassword.Text.Trim()))
            {
                PASSWORD = txtPassword.Text.Trim();
                txtPassword.Text = "";
                if (changePassword && !newLogin)
                {
                    PasswordToKey(PASSWORD);
                    if (CheckPassword(PASSWORD))
                    {
                        lblPaswd.Text = "Enter New Password";
                        lblPaswd.Refresh();
                        txtPassword.Text = "";
                        ShowPanels(panelsVal.NewPassword);
                    }
                    else
                    {
                        chkChangePaswd.Checked = true;
                        lblPaswd.Text = "Enter Old Password";
                        txtPassword.Text = "";
                    }
                }
                else
                {
                    PasswordToKey(PASSWORD);
                    ValidatePrivateMessage(newLogin);
                }
            }
            else
            {
                MessageBox.Show("Password can`t be left empty.", "ERROR");
            }
        }
        private bool CheckPassword(string password)
        {
            string command = "SELECT * FROM Password WHERE password = '" + password.Trim() + "'"; //Check password from database
            db.SetConnection(command, DB.sqlAction.Select, out tableRule);
            if (tableRule.Rows.Count < 1)
            {
                MessageBox.Show("Wrong Password", "ERROR");
                ShowPanels(panelsVal.Password);

                return false;
            }
            else
            {
                hideFolder = new HiddenFolderClass(password.Trim());
                return true;
            }
        }
        #endregion


        private void btnHide_Click(object sender, EventArgs e)
        {
            ShowPanels(panelsVal.None);
        }

        private void btnPaswdCancel_Click(object sender, EventArgs e)
        {
            ShowPanels(panelsVal.None);
        }

        private void btnPrivateClose_Click(object sender, EventArgs e)
        {
            ShowPanels(panelsVal.AllMessages); ;
        }

        private void listHide_ItemActivate(object sender, EventArgs e)
        {
            //txtPrivateMsg.Text = "";
            //txtPrivateMsg.Text = messagesAll[listHide.FocusedItem.Index];
            //ShowPanels(panelsVal.SingleMessage);
        }

        private void ShowPanels(panelsVal val)
        {
            switch (val)
            {
                case panelsVal.None:
                    panelPassword.Visible = false;
                    panelPassword.Hide();
                    panelPrivate.Visible = false;
                    panelPrivate.Enabled = false;
                    panelPrivate.Hide();
                    panelNewPassword.Visible = false;
                    panelNewPassword.SendToBack();
                    panelNewPassword.Hide();
                    panelSchedule.Visible = false;
                    panelSchedule.SendToBack();
                    panelSchedule.Hide();
                    panelBlack.Visible = false;
                    panelBlack.Hide();
                    panelBlack.SendToBack();
                    break;
                case panelsVal.AllMessages:
                    panelPassword.Visible = false;
                    panelPassword.SendToBack();
                    panelPassword.Hide();
                    panelPrivate.Visible = true;
                    panelPrivate.Enabled = true;
                    panelPrivate.BringToFront();
                    panelPrivate.Show();
                    panelNewPassword.Visible = false;
                    panelNewPassword.SendToBack();
                    panelNewPassword.Hide();
                    panelSchedule.Visible = false;
                    panelSchedule.SendToBack();
                    panelSchedule.Hide();
                    break;
                case panelsVal.Password:
                    panelPassword.Visible = true;
                    panelPassword.BringToFront();
                    panelPassword.Show();
                    panelPrivate.Visible = false;
                    panelPrivate.Enabled = false;
                    panelPrivate.SendToBack();
                    panelPrivate.Hide();
                    panelNewPassword.Visible = false;
                    panelNewPassword.SendToBack();
                    panelNewPassword.Hide();
                    panelSchedule.Visible = false;
                    panelSchedule.SendToBack();
                    panelSchedule.Hide();
                    break;
                case panelsVal.NewPassword:
                    panelPassword.Visible = true;
                    panelPassword.BringToFront();
                    panelPassword.Show();
                    panelNewPassword.Visible = true;
                    panelNewPassword.BringToFront();
                    panelNewPassword.Show();
                    panelPrivate.Visible = false;
                    panelPrivate.Enabled = false;
                    panelPrivate.SendToBack();
                    panelPrivate.Hide();
                    panelSchedule.Visible = false;
                    panelSchedule.SendToBack();
                    panelSchedule.Hide();
                    break;
            }
        }

        private void DeletePrivateMessages()
        {
            hideFolder.DeleteAllPrivateMessages();
        }

        private void Rules_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            HiddenFolderClass hf = new HiddenFolderClass();
            hf.HideMessageFromPrivateFolder();
            this.Dispose(true);
        }

        private void bttnSHOWPRIVFOL_Click(object sender, EventArgs e)
        {
            if (CheckIfPrivateFolderIsVisible())
            {
                hideFolder.HideMessageFromPrivateFolder();
            }
            else
            {
                ShowPrivateMessages();
                AlertUser();
            }
            bttnSHOWPRIVFOL.Refresh();
            ShowPanels(panelsVal.None);
        }

        private void AlertUser()
        {
            if (MessageBox.Show("Please check the PRIVATE folder in the SMS folders!", "PRIVATE", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) == DialogResult.OK)
            {
                OpenSMSInbox();
            }
            else
            {
                MessageBox.Show("The private folder will be visible till Create Rules is running!", "NOTE");
            }
        }

        private void panelPrivate_EnabledChanged(object sender, EventArgs e)
        {
            bttnSHOWPRIVFOL.Refresh();
            if (CheckIfPrivateFolderIsVisible())
            {
                bttnSHOWPRIVFOL.Text = "HIDE PRIVATE FOLDER";
            }
            else
            {
                bttnSHOWPRIVFOL.Text = "SHOW PRIVATE FOLDER";
            }
            bttnSHOWPRIVFOL.Refresh();
        }

        private bool CheckIfPrivateFolderIsVisible()
        {
            if (GetFolderId("PRIVATE") != null)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        private void bttnDeletePriMsg_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Are you sure you want to delete all private messages!", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
            if (result == DialogResult.Yes)
            {
                hideFolder.DeleteAllPrivateMessages();
            }
        }

        private void OpenSMSInbox()
        {
            Process inbox = new Process();
            inbox.StartInfo.FileName = @"\Windows\tmail.exe";
            inbox.StartInfo.UseShellExecute = true;
            inbox.StartInfo.Arguments = @"-service ""SMS"" ";
            inbox.Start();
        }

        private void btnWildOK_Click(object sender, EventArgs e)
        {
            listVContact.Items.Clear();
            //listContact.Items.Clear();
            //listContact.Items.Add(txtWildNumber.Text.ToUpper().Trim());
            listVContact.Items.Add(new ListViewItem(txtWildNumber.Text.ToUpper().Trim()));
            panelwild.Enabled = false;
            panelwild.Visible = false;
            panelwild.SendToBack();
            panelBlack.Visible = false;
            panelBlack.Enabled = false;
            panelBlack.SendToBack();
        }

        private void btnWildCancel_Click(object sender, EventArgs e)
        {
            panelwild.Enabled = false;
            panelwild.Visible = false;
            panelwild.SendToBack();
            panelBlack.Visible = false;
            panelBlack.Enabled = false;
            panelBlack.SendToBack();
        }

        private void ddlRuleOpts_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlRuleOpts.SelectedIndex == 3)
            {
                listFolder.Enabled = false;
            }
            else
            {
                listFolder.Enabled = true;
            }
        }

        private void listVContact_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listVContact.FocusedItem != null)
                lblContact.Text = listVContact.FocusedItem.Text.Trim();
            lblContact.Refresh();
        }

        #region TOOLS
        private void bttnFilterFolder_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(targetFolder.Trim()))
            {

                Process pc = new Process();
                pc.StartInfo = new ProcessStartInfo(location + @"\" + "SMSRules.exe", " overrideInbox " + "\"" + targetFolder + "\"");
                pc.Start();
            }
        }


        private void bttnArchive_Click(object sender, EventArgs e)
        {
            IMAPIFolder archiveFolder = OpenFolder(ARCHSMS);
            IMAPIFolder archiveSubfolder;
            IMAPIFolder clientFolder;
            HiddenFolderClass openMessages = new HiddenFolderClass();
            List<IMAPIMessageID> message = new List<IMAPIMessageID>();
            int selectedFolders = 0;
            int messagesArchived = 0;
            if (archiveFolder != null)
            {
                foreach (ListViewItem lv in listFolderArch.Items)
                {
                    if (lv.Checked)
                    {
                        clientFolder = OpenFolder(lv.SubItems[0].Text.Trim());
                        if (clientFolder != null)
                        {
                            IMAPIMessageID[] sourceMessages = openMessages.GetMessagesFromFolders(clientFolder);
                            if (sourceMessages.Length != 0)
                            {
                                archiveSubfolder = CreateArchiveSubFolders(archiveFolder, lv.SubItems[0].Text.Trim());
                                selectedFolders++;
                                foreach (IMAPIMessageID eachMessage in sourceMessages)
                                {
                                    message.Clear();
                                    message.Add(eachMessage);
                                    clientFolder.CopyMessages(message.ToArray(), archiveSubfolder, true);
                                    messagesArchived++;
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("Error creating/opening source folder", "Error");
                            return;
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Error creating/opening Archive folder", "Error");
                return;
            }
            MessageBox.Show(selectedFolders.ToString() + " folders & " + messagesArchived.ToString() + " messages archived", "Info");
            BttnClearArch_Click(null, null);
        }
        string targetFolder = string.Empty;
        private void ddlFilterFolder_SelectedIndexChanged(object sender, EventArgs e)
        {
            targetFolder = ddlFilterFolder.SelectedItem.ToString();
            //"overrideInbox"
            bttnFilterFolder.Text = "Filter " + targetFolder;
            bttnFilterFolder.Refresh();
        }

        private void BttnClearArch_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem folderItem in listFolderArch.Items)
            {
                folderItem.Checked = false;
            }
        }
        #endregion
      


       
        private void menuNotify_Click(object sender, EventArgs e)
        {
           // menuNotify.Checked = RegIsChecked("NOTIFY");
            object status = reg.GetValue("notify");
            if (menuNotify.Checked)
            {
                menuNotify.Checked = false;
                menuNotiHid.Checked = false;
                reg.SetValue("notify", 0);
                reg.SetValue("notifyHide", 0);
            }
            else
            {
                menuNotify.Checked = true;
                reg.SetValue("notify", 1);
            }
            reg.Flush();
        }

        private void menuNotiHid_Click(object sender, EventArgs e)
        {
            if (menuNotify.Checked)
            {
                object status = reg.GetValue("notifyHide");
                if (menuNotiHid.Checked)
                {
                    menuNotiHid.Checked = false;
                    reg.SetValue("notifyHide", 0);

                }
                else
                {
                    menuNotiHid.Checked = true;
                    reg.SetValue("notifyHide", 1);
                }
            }
            else
            {
                MessageBox.Show("Custom notifications should be enabled first","Notify");
            }
            reg.Flush();
        }

        private void menuDefNotify_Click(object sender, EventArgs e)
        {
            object status = reg.GetValue("notifyDef");
            if (menuDefNotify.Checked)
            {
                menuDefNotify.Checked = false;
                reg.SetValue("notifyDef", 0);
                SetMessageNotification(false);

            }
            else
            {
                menuDefNotify.Checked = true;
                reg.SetValue("notifyDef", 1);
                SetMessageNotification(true);
            }
            reg.Flush();
        }

        private void menu_SCHED_Click(object sender, EventArgs e)
        {
            
            if (panelSchedule.Visible)
            {
                ShowPanels(panelsVal.None);
            }
            else
            {
                ShowPanels(panelsVal.None);
                panelBlack.BringToFront();
                panelBlack.Visible = true;
                panelBlack.Show();
                panelSchedule.Visible = true;
                panelSchedule.Show();
                panelSchedule.BringToFront();
            }
        }

        private void bttnSchdCancel_Click(object sender, EventArgs e)
        {
            SapScheduler.Scheduler desch = new SapScheduler.Scheduler(location+"\\SMSRules.exe");
            ShowPanels(panelsVal.None);
            reg.SetValue("scheduleSet",0);
        }
        
        private void bttnSchSet_Click(object sender, EventArgs e)
        {
            
            int hour = ddlSchHr.SelectedIndex;
            int minute = ddlSchMin.SelectedIndex;
            DateTime scheduledTime;
            if (hour > DateTime.Now.Hour)
            {
                scheduledTime = DateTime.Now.AddDays(1);
                //next day
            }
            else if (minute >= DateTime.Now.Minute)
            {
                scheduledTime = DateTime.Now;
                //today
            }
            else
            {
                scheduledTime = DateTime.Now.AddDays(1);
                //next day
            }
            //scheduledTime = scheduledTime.AddDays(1);
            scheduledTime = new DateTime(scheduledTime.Year, scheduledTime.Month, scheduledTime.Day, hour, minute, 00);

            SapScheduler.Scheduler sch = new SapScheduler.Scheduler(scheduledTime, location + "\\SMSRules.exe", "sch");
            ShowPanels(panelsVal.None);
            reg.SetValue("scheduleSet", 1);
            schTime = ddlSchHr.SelectedItem.ToString() + ":" + ddlSchMin.SelectedItem.ToString();
            GetSetSchedule(true);
        }

        private void GetSetSchedule(bool set)
        {
            if (!set)
               schTime = reg.GetValue("schedule").ToString();
            else
                reg.SetValue("schedule",schTime);
        }

        private void menuRunType_Popup(object sender, EventArgs e)
        {
            GetSetSchedule(false);
            if (schTime != "")
            {
                ddlSchHr.SelectedIndex = int.Parse(schTime.Split(":".ToCharArray()).GetValue(0).ToString());
                ddlSchMin.SelectedIndex = int.Parse(schTime.Split(":".ToCharArray()).GetValue(1).ToString());
            }
            else
            {
                ddlSchHr.SelectedIndex = -1;
                ddlSchMin.SelectedIndex = -1;
            }

            object status = reg.GetValue("scheduleSet");
            if (status.ToString() == "0")
            {
                menu_SCHED.Checked = false;
            }
            else
            {
                menu_SCHED.Checked = true;
            }
        }

    }
}
